package self.hoy.demo.cloud.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import self.hoy.demo.cloud.constant.ApplicationInterface;
import self.hoy.demo.cloud.entities.CommonResult;
import self.hoy.demo.cloud.entities.Payment;
import self.hoy.demo.cloud.service.PaymentService;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 三共小不
 * @date 2020/5/29
 */
@RestController
@Slf4j
public class PaymentController implements ApplicationInterface {

    @Autowired
    private PaymentService paymentService;

    @Value("${server.port}")
    private String port;//用于区分不同端口的provider


    @Resource
    private DiscoveryClient discoveryClient;


    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        log.info("{} insert {} result is {}", port, payment== null ? "" : payment.getSerial(), result);
        if (result > 0) {
            return new CommonResult(CommonResult.SUCCESS, port+"添加成功！", result);
        }
        return new CommonResult(CommonResult.FAIL, "");
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
        Payment result = paymentService.getPaymentById(id);
        log.info("{} 查询Payment({})结果:{}", port, id, result);
        if (result == null) {
            return new CommonResult<Payment>(CommonResult.FAIL, null);
        }
        return new CommonResult<Payment>(CommonResult.SUCCESS, ""+port, result);
    }

    @GetMapping("/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info(service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances(PAYMENT_INSTANCE_NAME);
        for (ServiceInstance instance : instances) {
            log.info("instance-id:{}, host:port={}:{}, uri:{}", instance.getInstanceId(), instance.getHost(), instance.getPort(), instance.getUri());
        }
        return discoveryClient;
    }
}
